package com.ai.wxy.spring.auth.rest;

import com.ai.spring.common.util.EncryptUtils;
import com.ai.spring.common.util.ResponseResult;
import com.ai.spring.common.util.ResponseResultUtil;
import com.ai.wxy.spring.auth.dto.JwtUserDTO;
import com.ai.wxy.spring.auth.dto.UserDTO;
import com.ai.wxy.spring.auth.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 授权、根据token获取用户详细信息
 *
 * @author 石头
 * @Date 2019/10/31
 * @Version 1.0
 **/
@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthenticationController {
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping(value = "${jwt.auth.path:/login}")
    public ResponseResult<UserDTO> login(@Validated(UserDTO.Login.class) UserDTO authorizationUser){
        JwtUserDTO jwtUser = (JwtUserDTO)userDetailsService.loadUserByUsername(authorizationUser.getUsername());
        String loginPwd = authorizationUser.getPassword();
        if (jwtTokenUtil.getPwdEncrpyt()){
            loginPwd = EncryptUtils.encrypt(authorizationUser.getUsername(),loginPwd,EncryptUtils.SALT);
        }
        if (jwtUser==null || !jwtUser.getPassword().equals(loginPwd)){
            throw new AccountExpiredException("用户名或密码错误");
        }
        if(!jwtUser.isEnabled()){
            throw new AccountExpiredException("账号已停用，请联系管理员");
        }

        // 生成令牌
        final String token = jwtTokenUtil.generateToken(jwtUser);
        UserDTO result = new UserDTO();
        result.setId(jwtUser.getId());
        result.setUsername(jwtUser.getUsername());
        result.setToken(JwtTokenUtil.getTokenPrefix() + token);
        return ResponseResultUtil.ofSuccess(result);
    }
}
